#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

using namespace My_Log;
using namespace My_ThreadPool;

using adduser_t = std::function<void(const InetAddr &id)>;
using route_t = std::function<void(int sokfd, std::string &message)>;
using task_t = std::function<void()>;

const in_port_t defport = 8080;
const std::string defip = "127.0.0.1";

class UdpServer
{
public:
    UdpServer(in_port_t port = defport)
        : _sokfd(-1), _isrunning(false), _addr(port)
    {
    }
    void RegisterService(adduser_t adduser, route_t route)
    {
        _adduser = adduser;
        _route = route;
    }
    void InitServer()
    {
        _sokfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sokfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket err: " << strerror(errno);
            exit(SOCKET_ERR);
        }

        int n = bind(_sokfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = true;

        while (true)
        {
            char recbuff[1024] = {0};
            struct sockaddr_in cliaddr;
            socklen_t len = sizeof(cliaddr);
            int n = recvfrom(_sokfd, recbuff, 1024, 0, CONV(&cliaddr), &len);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "recvfrom err" << strerror(errno);
                exit(REC_ERR);
            }
            
            InetAddr cli(cliaddr);
            std::string message = std::string(cli.GetStrAddr() + " info: ") + recbuff;
            _adduser(cli);//创建用户User


            task_t task = bind(_route, _sokfd, message);
            ThreadPool<task_t>::getinstance()->Equeue(task);
            
            
            // LOG(LogLevel::DEBUG) << "Server receive " << cli.GetStrAddr() << "message# " << message;
            // sendto(_sokfd, recbuff, n, 0, CONV(&cliaddr), len);
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if (_sokfd > -1)
            close(_sokfd);
    }

private:
    int _sokfd;
    InetAddr _addr;
    bool _isrunning;

    adduser_t _adduser;
    route_t _route;
};